package com.myspring.resttest.dao.impl;

import java.util.List;

import javax.transaction.Transactional;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.myspring.resttest.dao.SpringHibernateUserDao;
import com.myspring.resttest.model.SpringHibernateUser;

@EnableTransactionManagement
@Service
public class SpringHibernateUserDaoImpl implements SpringHibernateUserDao {

	@Autowired
	SessionFactory sessionFactory;

	
	@Override
	public void insertUser(SpringHibernateUser user) {
		sessionFactory.getCurrentSession().save(user);
	}

	@Override
	public SpringHibernateUser getUserById(int userId) {
		return ((SpringHibernateUser) sessionFactory.getCurrentSession().get(
				SpringHibernateUser.class, userId));
	}

	@Override
	public SpringHibernateUser getUser(String username2) {
		Query query = sessionFactory.getCurrentSession().createQuery(
				"from SpringHibernateUser where username = :usernameparam");
		query.setParameter("usernameparam", username2);
		return (SpringHibernateUser) query.list().get(0);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<SpringHibernateUser> getUsers() {
		Criteria criteria = sessionFactory.
			      getCurrentSession().
			      createCriteria(SpringHibernateUser.class);
			    return criteria.list();
	}

}
